package li.com.springaidemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import li.com.springaidemo.common.R;
import li.com.springaidemo.pojo.MessageLog;
import li.com.springaidemo.pojo.Persona;
import li.com.springaidemo.pojo.User;
import li.com.springaidemo.pojo.vo.MessageVo;
import li.com.springaidemo.service.AIService;
import li.com.springaidemo.service.MessageService;
import li.com.springaidemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/messagevo")
public class MessageVoController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private AIService aiService;

    @GetMapping("/getAllMessage")
    public R getAllMessage(@RequestParam(value = "persona",defaultValue = "") String persona, @RequestParam(value = "userid",defaultValue = "") String userid){
        User user = userService.getById(userid);
        Persona topersona = aiService.getOne(new QueryWrapper<Persona>().eq("object_name", persona));
        QueryWrapper<MessageLog> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userid",userid).eq("personaname",persona);
        queryWrapper.orderByAsc("time");
        List<MessageLog> list = messageService.list(queryWrapper);
        List<MessageVo> voList = list.stream()
                .map(item -> {
                    MessageVo messageVo = new MessageVo();
                    messageVo.setUsername(user.getUsername());
                    messageVo.setUserimg(user.getImg());
                    messageVo.setPersonaname(topersona.getName());
                    messageVo.setPersonaimg(topersona.getImg());
                    messageVo.setText(item.getText());
                    messageVo.setTime(item.getTime());
                    messageVo.setType(item.getType());
                    return messageVo;
                }).collect(Collectors.toUnmodifiableList());
        return R.success(voList);
    }

    @GetMapping("/delAllMessage")
    public R delAllMessage(@RequestParam(value = "persona",defaultValue = "") String persona, @RequestParam(value = "userid",defaultValue = "") String userid){
        QueryWrapper<MessageLog> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userid",userid).eq("personaname",persona);
        messageService.remove(queryWrapper);
        return R.success();
    }
}
